<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4"> <category @tree-node-click="changeNodeClick"></category> </el-col>
        <el-col :span="20">
          <el-row :span="24">
            <el-form ref="form" :model="searchDto" :inline="true" label-width="auto">
              <el-form-item label="属性名称">
                <el-input
                  v-model="searchDto.attrName"
                  size="small"
                  placeholder="请输入属性名称"
                  prefix-icon="el-icon-search"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon"><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="是否需要检索">
                <el-select
                  v-model="searchDto.searchType"
                  size="small"
                  placeholder="请选择状态"
                  clearable
                  style="width: 100px"
                >
                  <el-option label="需要" :value="0" />
                  <el-option label="不需要" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" size="small" @click="onSearch"
                  >搜索</el-button
                >
                <el-button :icon="Refresh" size="small" @click="refresh">重置</el-button>
              </el-form-item>
            </el-form>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-button type="primary" plain :icon="Plus" size="small" @click="addAttrButton"
                >新增属性</el-button
              >
              <el-button type="info" plain :icon="BottomRight" size="small">导入</el-button>
              <el-button type="warning" plain :icon="TopRight" size="small">导出</el-button>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-table v-loading="loading" :data="tableData" border style="width: 100%">
              <el-table-column prop="attrName" label="属性名" width="150" align="center" />
              <el-table-column prop="catName" label="所属分类" width="150" align="center" />
              <el-table-column prop="attrGroupName" label="所属分组" width="150" align="center" />
              <el-table-column prop="icon" label="属性图标" width="150" align="center">
                <template #default="scope">
                  <el-icon :size="size" style="vertical-align: middle; margin-right: 8px">
                    <component :is="scope.row.icon" />
                  </el-icon>
                </template>
              </el-table-column>
              <el-table-column prop="enable" label="启用状态" width="150" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.enable === 0">启用</el-tag>
                  <el-tag v-else type="success">禁用</el-tag>
                </template>
                <!-- <el-switch v-model="value1"></el-switch> -->
              </el-table-column>
              <el-table-column prop="searchType" label="是否需要检索" width="150" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.searchType === 0">是</el-tag>
                  <el-tag v-else type="success">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="valueType" label="值类型" width="150" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.valueType === 0">单选</el-tag>
                  <el-tag v-else type="success">多选</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="valueSelect" label="可选值列表" width="150" align="center" />
              <el-table-column prop="attrType" label="属性类型" width="150" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.attrType === 0">销售属性</el-tag>
                  <el-tag v-else-if="scope.row.attrType === 1" type="success">规格参数</el-tag>
                  <el-tag v-else type="success">销售属性/基本属性</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="showDesc" label="是否快速展示" width="150" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.showDesc === 0">是</el-tag>
                  <el-tag v-else type="success">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" fixed="right" min-width="180">
                <template #default="scope">
                  <el-button size="small" type="warning" @click="editAttrButton(scope.row.attrId)"
                    >编辑</el-button
                  >
                  <el-button size="small" type="danger" @click="deleteAttrButton(scope.row.attrId)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-pagination
              v-model:current-page="pageNo"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :size="size"
              :background="background"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              style="margin-top: 10px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-col>
      </el-row>

      <!-- 弹窗 -->
      <el-dialog v-model="dialogVisible" :title="Tips" width="500" @close="handleClose">
        <el-form
          ref="ruleFormRef"
          :model="productAttr"
          label-width="auto"
          style="max-width: 600px"
          :rules="rules"
        >
          <el-form-item label="属性名称" prop="attrName">
            <el-input v-model="productAttr.attrName" placeholder="请输入属性名称"></el-input>
          </el-form-item>
          <el-form-item label="所属分类" prop="catId">
            <el-cascader
              v-model="productAttr.catId"
              :options="options"
              :props="cascaderProps"
              filterable
              @change="changeAttr"
            />
          </el-form-item>
          <el-form-item label="所属分组" prop="attrGroupId">
            <el-select v-model="productAttr.attrGroupId" placeholder="请选择所属分组">
              <el-option
                v-for="item in attrGroupOptions"
                :key="item.attrGroupId"
                :label="item.attrGroupName"
                :value="item.attrGroupId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="可选值类型" prop="valueType">
            <el-select v-model="productAttr.valueType" placeholder="请选择状态">
              <el-option label="单个值" :value="0" />
              <el-option label="多个值" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="可选值列表" prop="valueSelect">
            <el-input v-model="productAttr.valueSelect" placeholder="可选值列表"></el-input>
          </el-form-item>
          <el-form-item label="属性图标" prop="icon">
            <SelectIcon
              v-model="productAttr.icon"
              :size="20"
              :width="200"
              placeholder="请选择一个图标"
              :preview-size="32"
              :preview-margin-top="12"
            />
          </el-form-item>
          <el-form-item label="是否需要检索" prop="searchType">
            <el-select v-model="productAttr.searchType" placeholder="请选择状态">
              <el-option label="需要" :value="0" />
              <el-option label="不需要" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="启用状态">
            <el-switch
              v-model="productAttr.enable"
              active-text="启用"
              inactive-text="禁用"
              class="ml-2"
              :active-value="0"
              :inactive-value="1"
            />
          </el-form-item>
          <el-form-item label="是否快速展示" prop="showDesc">
            <el-radio-group v-model="productAttr.showDesc">
              <el-radio :value="0">是</el-radio>
              <el-radio :value="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitData"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { findCatIdGetAttrGroup } from '@/api/attrGroup'
import { categoryList } from '@/api/category'
import category from '@/components/common/category.vue'
import { Search, Refresh, Plus, BottomRight, TopRight } from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  attrSpecificationsList,
  attrSpecificationsAdd,
  attrSpecificationsUpdate,
  getSpecificationsAttrId,
  attrSpecificationsDelete
} from '@/api/attr'
import SelectIcon from '@/components/common/select-icon.vue'
const cascaderProps = {
  multiple: false, //是否可以多选，false:单选，true:多选
  checkStrictly: false, // false不允许选择任意级别,只能选择最后一级
  value: 'catId',
  label: 'name',
  children: 'children',
  emitPath: false //在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}
//分类多级列表
const options = ref([])
//表格组件实例对象
const form = ref(null)
//搜索对象
const searchDto = ref({
  // 属性名称
  attrName: '',
  // 是否需要检索[0-需要，1-不需要]
  searchType: null,
  // 分类id
  catId: null
})
//加载状态 默认为false
const loading = ref(false)
//表格数据
const tableData = ref([])
// 分页器当前的页码数
const pageNo = ref(1)
// 分页器每页显示多少条数据
const pageSize = ref(10)
//分页器大小
const size = ref('default')
//分页器背景样式
const background = ref(true)
// 总数据条数
const totalCount = ref(0)
// 弹窗标题
const Tips = ref('')
// 弹窗显示状态
const dialogVisible = ref(false)
// 弹窗表单对象实例
const ruleFormRef = ref(null)
//对话框类型:作用用来提交数据时候，区分是修改还是添加
const dialogType = ref('')
// 弹窗表单数据
const productAttr = ref({
  attrId: null,
  attrName: '',
  searchType: 0,
  valueType: 0,
  icon: '',
  valueSelect: '',
  enable: 0,
  showDesc: 0,
  catId: null,
  attrGroupId: null
})
/**
 * 表单验证规则
 */
const rules = reactive({
  attrName: [{ required: true, message: '请输入属性名称', trigger: 'blur' }],
  catId: [{ required: true, message: '请选择所属分类', trigger: 'blur' }],
  attrGroupId: [{ required: true, message: '请选择所属分类下的分组', trigger: 'blur' }],
  searchType: [{ required: true, message: '请选择是否需要检索', trigger: 'blur' }],
  valueType: [{ required: true, message: '请选择值的类型', trigger: 'blur' }],
  icon: [{ required: true, message: '请选择上传的图标', trigger: 'blur' }],
  valueSelect: [{ required: true, message: '可选值列表', trigger: 'blur' }]
})
/**
 * 点击左侧的树节点，回调方法
 * @param data
 */
const changeNodeClick = data => {
  // console.log('父组件感知到子组件传递过来的数据')
  // console.log(data)
  // console.log(data.catId)
  if (data.catLevel === 3) {
    searchDto.value.catId = data.catId
  }
}
/**
 * 分页器每页显示多少条数据发生改变
 */
const handleSizeChange = () => {
  console.log('每页可展示的条数发生改变', pageSize.value)
  attrPageList()
}
/**
 * 分页器当前页码数发生改变
 */
const handleCurrentChange = () => {
  console.log('页码数发生改变', pageNo.value)
  attrPageList()
}
/**
 * 搜索
 */
const onSearch = () => {
  console.log('搜索')
  attrPageList()
}
/**
 * 重置
 */
const refresh = () => {
  console.log('重置')
  searchDto.value = {}
  attrPageList()
}
/**
 * 新增按钮
 */
const addAttrButton = async () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  options.value = await categoryList()
}
/**
 * 编辑按钮
 */
const editAttrButton = async attrId => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  options.value = await categoryList()
  productAttr.value = await getSpecificationsAttrId(attrId)
}
/**
 * 删除按钮
 */
const deleteAttrButton = attrId => {
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 确定
      await attrSpecificationsDelete(attrId)

      ElMessage.success('删除成功')
      await attrPageList()
    })
    .catch(() => {
      // 取消
      ElMessage.info('已取消删除')
    })
}
/**
 * 确定按钮,提交数据
 */
const submitData = async () => {
  if (!ruleFormRef.value) return
  try {
    // 如果校验失败，这里会 throw
    await ruleFormRef.value.validate()
    // 校验通过
    // … 发接口、关闭弹窗之类的
    console.log('校验通过，开始提交')

    if (dialogType.value == 'add') {
      await saveAttr()
    } else {
      await editAttr()
    }
    dialogVisible.value = false
    //刷新页面列表
    await attrPageList()
  } catch (err) {
    // 校验不通过或其它错误都会走到这
    console.warn('校验失败：', err)
    ElMessage.error('请检查表单必填项或格式')
  }
}
const attrPageList = async () => {
  const { records, total } = await attrSpecificationsList(
    pageNo.value,
    pageSize.value,
    searchDto.value
  )
  tableData.value = records
  totalCount.value = total
}
const saveAttr = async () => {
  await attrSpecificationsAdd(productAttr.value)
  ElMessage({
    type: 'success',
    message: '添加成功'
  })
}
const editAttr = async () => {
  await attrSpecificationsUpdate(productAttr.value)
  ElMessage({
    type: 'success',
    message: '修改成功'
  })
}
/**
 * 弹窗关闭
 */
const handleClose = () => {
  console.log('关闭弹窗')
  dialogVisible.value = false
  dialogType.value = ''
  productAttr.value = {
    attrId: null,
    attrName: '',
    searchType: 0,
    valueType: 0,
    icon: '',
    valueSelect: '',
    enable: 0,
    showDesc: 0,
    attrGroupId: null
  }
}

/**
 * 根据上面的所选择的分类获取分类下的分组选项信息
 */
const attrGroupOptions = ref([])
const changeAttr = async () => {
  attrGroupOptions.value = await findCatIdGetAttrGroup(productAttr.value.catId)
}

onMounted(() => {
  attrPageList()
})
</script>
